package com.wjk.girl.controller.wechat;


import com.wjk.girl.utils.wechat.WeixinJavaTools;
import com.wjk.girl.utils.wechat.WeixinUtil;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;


@RestController
@RequestMapping("/wechat")
public class WechatController {
    @Autowired
    private WxMpService wxMpService;
    Logger logger = LoggerFactory.getLogger(WechatController.class);
    @GetMapping("/authorize")
    public void authorize(HttpServletResponse response) throws IOException {
        String url = "http://wangjiankun.tunnel.echomod.cn/girl/wechat/userInfo";
        String redirectURL = "";
            redirectURL = wxMpService.oauth2buildAuthorizationUrl(url,
                    WxConsts.OAuth2Scope.SNSAPI_USERINFO, null);
        logger.info("【微信网页授权】获取code,redirectURL={}", redirectURL);
        response.sendRedirect(redirectURL);
        //return "redirect:" + redirectURL;
    }
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code) throws Exception {
        logger.info("【微信网页授权】code={}", code);
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken;
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
        } catch (WxErrorException e) {
            logger.info("【微信网页授权】{}", e);
            throw new Exception(e.getError().getErrorMsg());
        }
        String openId = wxMpOAuth2AccessToken.getOpenId();
        logger.info("【微信网页授权】openId={}", openId);
        //
        WxMpUser wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        String city = wxMpUser.getCity();
        return city;
        //return "redirect:" + returnUrl + "?openid=" + openId;
    }

    @RequestMapping(value = "/getUserInfo")
    public void getWechetInfo(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("code");//微信活返回code值，用code获取openid
        Map<String,String> map = new HashMap<>();
        map = WeixinUtil.getOauth(code);
        String openId = map.get("openid");
        String access_token = map.get("access_token");
        JSONObject obj = WeixinUtil.getUserDetalsInfo(access_token,openId);
        System.out.println("!!!!!!"+obj.toString());
    }
    @GetMapping(value = "/validate")
    public void validateWechatGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String signature = request.getParameter("signature");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        String echostr = request.getParameter("echostr");
        /*if(CheckUtil.checkSignature(signature,timestamp,nonce)){
            response.getWriter().print(echostr);
        }*/
        //微信工具类
        WxMpService wxService=new WxMpServiceImpl();
        WxMpInMemoryConfigStorage wxConfigProvider=new WxMpInMemoryConfigStorage();
        //注入token值
        wxConfigProvider.setToken("wjk");
        wxService.setWxMpConfigStorage(wxConfigProvider);
        boolean flag=wxService.checkSignature(timestamp, nonce, signature);
        PrintWriter out=response.getWriter();
        if(flag){
            out.print(echostr);
        }
        out.close();
        out=null;
    }
    @PostMapping(value = "/validate")
    public void validateWechatPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        WxMpXmlMessage message = WxMpXmlMessage.fromXml(request.getInputStream());
        String messageType = message.getMsgType();
        String fromUser = message.getFromUser();
        String toUser = message.getToUser();
        String content = message.getContent();
        WeixinJavaTools.doService(message,response);
    }
    @RequestMapping(value = "/getOauthUrl")
    public static void getOauthUrl(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String url = WeixinUtil.getOpenidUrl();
        System.out.println("微信网址："+url);

        response.sendRedirect(url);
    }
}
